package com.c.yinyuezhushou.Ui;


import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.airbnb.lottie.LottieAnimationView;
import com.bumptech.glide.Glide;
import com.c.yinyuezhushou.Dialog.LsListDialog;
import com.c.yinyuezhushou.Fragment.MineFragment;
import com.c.yinyuezhushou.Fragment.MusicFragment;
import com.c.yinyuezhushou.MyApplication;
import com.c.yinyuezhushou.R;
import com.c.yinyuezhushou.MRetrofit.MusicItem;

import com.c.yinyuezhushou.Service.DownService;
import com.c.yinyuezhushou.Service.MusicService;
import com.google.android.material.tabs.TabLayout;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class HomeActivity extends AppCompatActivity{
    String[] perms1 = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private TabLayout tabLayout;
    private CardView cardView;
    private ImageView imageView1;
    private ImageView imageView2;
    private CircleImageView circleImageView;
    private TextView textView;
    private TextView textView1;
    private ProgressBar progressBar;
    private MusicService musicService;
    private MusicFragment musicFragment;
    private MusicService.MusicServiceIBinder iBinder;
    final String[] tabdata = {"听歌","我的"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        permisssions();

        cardView = findViewById(R.id.main_card);
        tabLayout = findViewById(R.id.home_tabs);
        imageView1 = findViewById(R.id.main_image1);
        imageView2 = findViewById(R.id.main_image2);
        circleImageView = findViewById(R.id.main_circle);
        textView = findViewById(R.id.main_text);
        textView1 =findViewById(R.id.main_text1);
        progressBar =findViewById(R.id.main_pro);

        try {
            Intent intent1 = new Intent(this, DownService.class);
            startService(intent1);
            bindService(intent1, DownServiceConnection, BIND_AUTO_CREATE);
        }catch (Exception e){
            e.printStackTrace();
        }


        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

        setOnOnClickListener();

    }



    private void setTabLayout(){
        TabLayout.Tab tab = tabLayout.newTab();
        View view = View.inflate(this,R.layout.item_tabs_homeactivity,null) ;
        TextView textView = view.findViewById(R.id.home_tabs_textview);
        textView.setText(tabdata[0]);
        LottieAnimationView lottieAnimationView=view.findViewById(R.id.home_tabs_lottie);
        lottieAnimationView.setAnimation(R.raw.icon_music);
        lottieAnimationView.loop(false);//设置动画是否循环播放，true表示循环播放，false表示只播放一次
        tab.setTag("main_tablayout_0");
        tab.setCustomView(view);
        tabLayout.addTab(tab);
        tab = tabLayout.newTab();
        view = View.inflate(this,R.layout.item_tabs_homeactivity,null) ;
        textView = view.findViewById(R.id.home_tabs_textview);
        textView.setText(tabdata[1]);
        lottieAnimationView=view.findViewById(R.id.home_tabs_lottie);
        Glide.with(this).load(R.drawable.icon_mine1).into(lottieAnimationView);
        lottieAnimationView.loop(false);//设置动画是否循环播放，true表示循环播放，false表示只播放一次
        tab.setTag("main_tablayout_1");
        tab.setCustomView(view);
        tabLayout.addTab(tab);

        List<Fragment> list = new ArrayList<>();
        final MineFragment mineFragment = new MineFragment();
        musicFragment = new MusicFragment(musicService,this);

        final FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        ft.add(R.id.main_flayot,musicFragment);
        ft.add(R.id.main_flayot,mineFragment);

        ft.hide(mineFragment);
        ft.show(musicFragment);

        ft.commit();

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                LottieAnimationView lottieAnimationView1=tab.getCustomView().findViewById(R.id.home_tabs_lottie);
                FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
                if (tab.getTag().toString().equals("main_tablayout_0")){
                    lottieAnimationView1.setAnimation(R.raw.icon_music);
                    ft.show(musicFragment);
                    ft.hide(mineFragment);
                }else {
                    lottieAnimationView1.setAnimation(R.raw.icon_mine);
                    ft.show(mineFragment);
                    ft.hide(musicFragment);
                }
                lottieAnimationView1.playAnimation();
                ft.commit();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                LottieAnimationView lottieAnimationView1 = tab.getCustomView().findViewById(R.id.home_tabs_lottie);
                if (tab.getTag().toString().equals("main_tablayout_0")){
                    Glide.with(HomeActivity.this).load(R.drawable.icon_music1).into(lottieAnimationView1);
                }else{
                    Glide.with(HomeActivity.this).load(R.drawable.icon_mine1).into(lottieAnimationView1);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                LottieAnimationView lottieAnimationView1=tab.getCustomView().findViewById(R.id.home_tabs_lottie);
                lottieAnimationView1.playAnimation();
            }
        });
    }
    private void setOnOnClickListener(){

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeActivity.this,PlayerActivity.class);
                startActivity(intent);
            }
        });

        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (musicService.getLslist()!=null){
                    List<MusicItem> list = musicService.getLslist();
                    LsListDialog lsListDialog = new LsListDialog(list,musicService);
                    lsListDialog.show(getSupportFragmentManager(),"播放记录");
                }
            }
        });

        imageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                musicService.start();
            }
        });

    }

    private void permisssions(){
        if (ContextCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(HomeActivity.this, perms1, 100);
                //没有授权，编写申请权限代码
        }else {
            MyApplication myApplication = (MyApplication)getApplicationContext();
            File file = new File(myApplication.getSetup().getPath());
            if (!file.exists()){
                file.mkdirs();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode ==100){
            if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                //授权成功，
                Toast.makeText(this, "下起来！！", Toast.LENGTH_SHORT).show();
                MyApplication myApplication = (MyApplication)getApplicationContext();
                File file = new File(myApplication.getSetup().getPath());
                if (!file.exists()){
                    file.mkdirs();
                }
            }else{
                Toast.makeText(this, "人间不值得", Toast.LENGTH_SHORT).show();

            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private ServiceConnection DownServiceConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            DownService.DownServiceIBinder iBinder1= (DownService.DownServiceIBinder) iBinder;
            DownService downService = iBinder1.getDownService();
            MyApplication myApplication = (MyApplication)getApplicationContext();
            myApplication.setDownService(downService);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    private ServiceConnection mServiceConnection = new ServiceConnection()
    {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iBinder = (MusicService.MusicServiceIBinder) service;
            musicService = iBinder.getMusicService();

            MyApplication myApplication = (MyApplication)getApplicationContext();
            myApplication.setMusicService(musicService);

            musicService.prepareToPlay1(musicService.getSql());

            musicService.addOnStateChangeListenerInner(new MusicService.OnStateChangeListenr() {
                @Override
                public void onPlay(long time) {
                    MusicItem musicItem1 = musicService.getMusicItem();
                    progressBar.setMax((int)time);
                    progressBar.setProgress(0);

                    Glide.with(HomeActivity.this).load(musicItem1.getImageurl()).into(circleImageView);
                    textView.setText(musicItem1.getSong());
                    textView1.setText(" - "+musicItem1.getSinger());

                }
                @Override
                public void onPlayComplete() {

                }

                @Override
                public void onStateChange(boolean isplay, long nowtime) {
                    if (isplay){
                        imageView2.setImageResource(R.drawable.icon_playing);
                        progressBar.setProgress((int)nowtime);
                    }else{
                        imageView2.setImageResource(R.drawable.icon_playing2);
                        progressBar.setProgress((int)nowtime);
                    }
                }

                @Override
                public void onSchedule(long nowtime) {
                    progressBar.setMax(musicService.getMusicPlayer().getDuration());
                    progressBar.setProgress((int)nowtime);
                }

                @Override
                public void OnTimeVariety(long nowtime) {
                    progressBar.setProgress((int) nowtime);
                }

                @Override
                public void loadfinised() {
                    MusicItem musicItem1 = musicService.getMusicItem();
                    textView.setText(musicItem1.getSong());
                    textView1.setText(" - "+musicItem1.getSinger());
                    progressBar.setMax(musicService.getMusicPlayer().getDuration());
                    Glide.with(HomeActivity.this).load(musicItem1.getImageurl()).into(circleImageView);
                }
            });

            setTabLayout();
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("test1","5656");
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}